package com.custompictureselector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.luck.picture.lib.PictureSelectorFragment;
import com.luck.picture.lib.basic.FragmentInjectManager;
import com.luck.picture.lib.basic.PictureCommonFragment;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.basic.PictureSelectorSupporterActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.interfaces.OnCameraInterceptListener;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DensityUtil;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.language.LanguageConfig;
import com.luck.picture.lib.style.SelectMainStyle;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

public class PictureSelectorModule extends ReactContextBaseJavaModule implements ActivityEventListener {

    private static final String REACT_CLASS = "CustomPictureSelector";
    private static final int REQUEST_CODE = 1001;
    private Promise mPromise;
    private PictureSelectorStyle selectorStyle;
    /* 选择器的回调fragment */
    private PictureSelectorFragment selectorFragment;
    private int selectorRequestCode;
    private Activity selectorFragmentActivity;

    public PictureSelectorModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addActivityEventListener(this);
    }

    @NonNull
    @Override
    public String getName() {
        return REACT_CLASS;
    }

    // 可选：导出常量
    @Nullable
    @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();
        constants.put("SELECT_SUCCESS", "select_success");
        constants.put("SELECT_CANCEL", "select_cancel");
        return constants;
    }

    // 打开图片选择器（Promise 方式）
    @ReactMethod
    public void openImageSelector(ReadableMap options, Promise promise) {
        mPromise = promise;
        Activity currentActivity = getCurrentActivity();

        if (currentActivity == null) {
            promise.reject("E_ACTIVITY_NOT_AVAILABLE", "Activity not available");
            return;
        }
        Log.d("selector", options.toString());
        setSelectMainStyle();

        int maxSelectNum = options.getInt("maxSelectNum");
        int imageSelectType = options.getInt("imageSelectType");
        boolean isUseOnCustomerCamera = options.getBoolean("isUseOnCustomerCamera");

        Log.d("selector", "create");

        OnCameraInterceptListener onCameraInterceptListener = new OnCameraInterceptListener() {
            @Override
            public void openCamera(Fragment fragment, int cameraMode, int requestCode) {
                // 注意* 如果你实现自己的拍照库，需要在Activity的.setResult(); 给Intent MediaStore.EXTRA_OUTPUT 保存拍照后的路径；
                Log.d("selector", "openCamera cameraMode:" +cameraMode);
                if (cameraMode == SelectMimeType.ofAudio()) {
                    Toast.makeText(getContext(), "自定义录音功能，请自行扩展", Toast.LENGTH_LONG).show();
                }
                else if(cameraMode == SelectMimeType.ofImage()) {
                    Log.d("selector", "openCamera 自定义拍照");
                    // 只实现拍照，视频请改上级代码
                    // 发起回调给js，让js拍照后回调给pictureSelector
                    sendEvent("pictureSelector_selectCustomCamera", null);
                    selectorFragment =  (PictureSelectorFragment) fragment;
                    selectorRequestCode = requestCode;

//                    selectorFragment.getView().setVisibility(View.INVISIBLE);
//                    currentActivity.setVisible(true);
                    Intent intent = new Intent(selectorFragment.getActivity(), currentActivity.getClass());
                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    selectorFragment.startActivity(intent);
//                    selectorFragmentActivity = selectorFragment.getActivity();
                    // TODO这里只实现自定义拍照，并关闭


                    //                    Intent intent = new Intent();
                    //                    Uri uri = Uri.parse("file:///data/user/0/com.taro73/cache/水印拍照F280BF6E4AD75242F1DC48349D79DA91.jpg");
                    //                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    //                    fragment.getActivity().setResult(requestCode, intent);
                    //                    PictureSelectorFragment selectorFragment = (PictureSelectorFragment) fragment;
                    //                    selectorFragment.dispatchHandleCamera(intent);

                } else if (cameraMode == SelectMimeType.TYPE_VIDEO) {
                    Log.d("selector", "openCamera 自定义录像");
                    sendEvent("pictureSelector_selectCustomVideoCamera", null);
                    selectorFragment =  (PictureSelectorFragment) fragment;
                    selectorRequestCode = requestCode;
                    Intent intent = new Intent(selectorFragment.getActivity(), currentActivity.getClass());
                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    selectorFragment.startActivity(intent);
                }

            }
        };
        if(!isUseOnCustomerCamera){
            onCameraInterceptListener = null;
        }
        PictureSelector.create(currentActivity)
                .openGallery(imageSelectType)// SelectMimeType.ofAll()
                .isWebp(false)
                .isGif(true)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setSelectorUIStyle(selectorStyle)
                .setMaxSelectNum(maxSelectNum)
                .setMaxVideoSelectNum(maxSelectNum)
                .setLanguage(LanguageConfig.CHINESE)
                .setCameraInterceptListener(onCameraInterceptListener)
                .isWithSelectVideoImage(true) // 视频图片同时选
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        WritableArray array = Arguments.createArray();
                        for (LocalMedia media : result) {
                            WritableMap map = Arguments.createMap();
                            map.putDouble("id", media.getId());
                            map.putString("path", media.getPath());
                            map.putString("realPath", media.getRealPath());
                            map.putString("originalPath", media.getOriginalPath());
                            map.putString("compressPath", media.getCompressPath());
                            map.putString("cutPath", media.getCutPath());
                            map.putString("watermarkPath", media.getWatermarkPath());
                            map.putString("videoThumbnailPath", media.getVideoThumbnailPath());
                            map.putString("sandboxPath", media.getSandboxPath());
                            map.putDouble("duration", media.getDuration());
                            map.putBoolean("isChecked", media.isChecked());
                            map.putBoolean("isCut", media.isCut());
                            map.putInt("position", media.getPosition());
                            map.putInt("num", media.getNum());
                            map.putString("mimeType", media.getMimeType());
                            map.putInt("chooseModel", media.getChooseModel());
                            map.putBoolean("isCameraSource", media.isCameraSource());
                            map.putBoolean("compressed", media.isCompressed());
                            map.putInt("width", media.getWidth());
                            map.putInt("height", media.getHeight());
                            map.putInt("cropImageWidth", media.getCropImageWidth());
                            map.putInt("cropImageHeight", media.getCropImageHeight());
                            map.putInt("cropOffsetX", media.getCropOffsetX());
                            map.putInt("cropOffsetY", media.getCropOffsetY());
                            map.putDouble("cropResultAspectRatio", media.getCropResultAspectRatio());
                            map.putDouble("size", media.getSize());
                            map.putBoolean("isOriginal", media.isOriginal());
                            map.putString("fileName", media.getFileName());
                            map.putString("parentFolderName", media.getParentFolderName());
                            map.putDouble("bucketId", media.getBucketId());
                            map.putDouble("dateAddedTime", media.getDateAddedTime());
                            map.putString("customData", media.getCustomData());
                            map.putBoolean("isMaxSelectEnabledMask", media.isMaxSelectEnabledMask());
                            map.putBoolean("isGalleryEnabledMask", media.isGalleryEnabledMask());
                            map.putBoolean("isEditorImage", media.isEditorImage());

                            array.pushMap(map);
                        }
                        promise.resolve(array);
                        if(selectorFragment!=null && selectorFragment.getActivity()!=null){
                            selectorFragment.getActivity().finish();
                            selectorFragment = null;
                            selectorFragmentActivity= null;
                        }


                    }

                    @Override
                    public void onCancel() {
                        promise.reject("E_USER_CANCELLED", "User cancelled selection");
                    }
                });
    }

    public Context getContext() {
        return getReactApplicationContext();
    }

    // 创建selectType
    private void setSelectMainStyle() {
        try {
            selectorStyle = new PictureSelectorStyle();
            // 微信主体风格
            SelectMainStyle numberSelectMainStyle = new SelectMainStyle();
            numberSelectMainStyle.setSelectNumberStyle(true);
            numberSelectMainStyle.setPreviewSelectNumberStyle(false);
            numberSelectMainStyle.setPreviewDisplaySelectGallery(true);
            numberSelectMainStyle.setSelectBackground(R.drawable.ps_default_num_selector);
            numberSelectMainStyle.setPreviewSelectBackground(R.drawable.ps_preview_checkbox_selector);
            numberSelectMainStyle.setSelectNormalBackgroundResources(R.drawable.ps_select_complete_normal_bg);
            numberSelectMainStyle.setSelectNormalTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_53575e));
            numberSelectMainStyle.setSelectNormalText(R.string.ps_send);
            numberSelectMainStyle.setAdapterPreviewGalleryBackgroundResource(R.drawable.ps_preview_gallery_bg);
            numberSelectMainStyle.setAdapterPreviewGalleryItemSize(DensityUtil.dip2px(getContext(), 52));
            numberSelectMainStyle.setPreviewSelectText(R.string.ps_select);
            numberSelectMainStyle.setPreviewSelectTextSize(14);
            numberSelectMainStyle.setPreviewSelectTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_white));
            numberSelectMainStyle.setPreviewSelectMarginRight(DensityUtil.dip2px(getContext(), 6));
            numberSelectMainStyle.setSelectBackgroundResources(R.drawable.ps_select_complete_bg);
            numberSelectMainStyle.setSelectText(R.string.ps_send_num);
            numberSelectMainStyle.setSelectTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_white));
            numberSelectMainStyle.setMainListBackgroundColor(ContextCompat.getColor(getContext(), R.color.ps_color_black));
            numberSelectMainStyle.setCompleteSelectRelativeTop(true);
            numberSelectMainStyle.setPreviewSelectRelativeBottom(true);
            numberSelectMainStyle.setAdapterItemIncludeEdge(false);

            // 头部TitleBar 风格
            TitleBarStyle numberTitleBarStyle = new TitleBarStyle();
            numberTitleBarStyle.setHideCancelButton(true);
            numberTitleBarStyle.setAlbumTitleRelativeLeft(true);
    //        if (cb_only_dir.isChecked()) {
    //            numberTitleBarStyle.setTitleAlbumBackgroundResource(R.drawable.ps_demo_only_album_bg);
    //        } else {
                numberTitleBarStyle.setTitleAlbumBackgroundResource(R.drawable.ps_album_bg);
    //        }
            numberTitleBarStyle.setTitleDrawableRightResource(R.drawable.ps_ic_grey_arrow);
            numberTitleBarStyle.setPreviewTitleLeftBackResource(R.drawable.ps_ic_normal_back);

            // 底部NavBar 风格
            BottomNavBarStyle numberBottomNavBarStyle = new BottomNavBarStyle();
            numberBottomNavBarStyle.setBottomPreviewNarBarBackgroundColor(ContextCompat.getColor(getContext(), R.color.ps_color_half_grey));
            numberBottomNavBarStyle.setBottomPreviewNormalText(R.string.ps_preview);
            numberBottomNavBarStyle.setBottomPreviewNormalTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_9b));
            numberBottomNavBarStyle.setBottomPreviewNormalTextSize(16);
            numberBottomNavBarStyle.setCompleteCountTips(false);
            numberBottomNavBarStyle.setBottomPreviewSelectText(R.string.ps_preview_num);
            numberBottomNavBarStyle.setBottomPreviewSelectTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_white));


            selectorStyle.setTitleBarStyle(numberTitleBarStyle);
            selectorStyle.setBottomBarStyle(numberBottomNavBarStyle);
            selectorStyle.setSelectMainStyle(numberSelectMainStyle);
        }  catch (Exception e) {
            e.printStackTrace();
        }

    }
    // 打开图片选择器（事件方式）

    private void sendEvent(String eventName, @Nullable Object params) {
        getReactApplicationContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    /**
     * js拍照成功后，发给 native
     * @param options
     * @param promise
     */
    @ReactMethod
    public void jsFinishTakePhoto(ReadableMap options, Promise promise) {
        String filePath = options.getString("filePath");
        Log.d("selector", "jsFinishTakePhoto filePath "+filePath);
        promise.resolve(true);

        Log.d("selector", "jsFinishTakePhoto 跳转回selector界面 ");
        // 跳转回selector界面
        //        Intent intent1 = new Intent(getCurrentActivity(), PictureSelectorSupporterActivity.class);
        //        intent1.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        //        getCurrentActivity().startActivity(intent1);

        Log.d("selector", "设置回调filePath");
        if( selectorFragment.getActivity()==null){
            Log.d("selector", "selectorFragment.getActivity() null" );
        }
        Log.d("selector", "selectorFragment.isAdded() "+ selectorFragment.isAdded());
        Intent intent = new Intent();
        // Uri uri = Uri.parse("file:///data/user/0/com.taro73/cache/水印拍照F280BF6E4AD75242F1DC48349D79DA91.jpg");
        Uri uri = Uri.parse(filePath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        Log.d("selector", "selectorFragment.setResult" );
        selectorFragment.getActivity().setResult(selectorRequestCode, intent);
        Log.d("selector", "selectorFragment.dispatchHandleCamera" );
        selectorFragment.dispatchHandleCamera(intent);
        Log.d("selector", "设置回调filePath end");
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        // 如果使用旧版 PictureSelector（不支持回调接口），需要在这里处理结果
    }

    @Override
    public void onNewIntent(Intent intent) {
        // 不需要处理
    }

    @ReactMethod
    public void addListener(String name) {
    }

    @ReactMethod
    public void removeListeners(Integer count) {
    }

    @ReactMethod
    public void afterCloseCustomerCamera() {
        try {
            Log.d("selector", "afterCloseCustomerCamera");
            // 判断最上方的activity是否PictureSelectorSupporterActivity
            if ((getCurrentActivity() instanceof PictureSelectorSupporterActivity)) {
                Log.d("selector", "afterCloseCustomerCamera 已经是，防止重复 运行");
                return;
            }

            Intent intent1 = new Intent(getCurrentActivity(), PictureSelectorSupporterActivity.class);
            intent1.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
            getCurrentActivity().startActivity(intent1);
            Log.d("selector", "afterCloseCustomerCamera end");
        } catch (Exception e) {
            Log.d("selector", "afterCloseCustomerCamera error");
            Toast.makeText(getCurrentActivity(), "异常不能跳转selector"+e.getMessage(), Toast.LENGTH_SHORT).show();
            throw new RuntimeException(e);
        }
    }
}